import axios from 'axios'
import {useUserStore} from "@/stores/user.js";

let userStore = null;
const service = axios.create({
    baseURL: import.meta.env.VITE_APP_API_BASE_URL,
    timeout: 5000
})

export function encodeSearchParams(obj) {
    if (!obj) return ''
    const params = []

    Object.keys(obj).forEach((key) => {
        let value = obj[key]
        // 如果值为undefined我们将其置空
        if (typeof value === 'undefined') {
            value = ''
        }
        // 去掉空串，不编码
        if (!value){
            return;
        }
        // 对于需要编码的文本（比如说中文）我们要进行编码
        params.push([key, encodeURIComponent(value)].join('='))
    })

    return params.join('&')
}

// 请求拦截器
service.interceptors.request.use(
    config => {
        const token = localStorage.getItem('token')
        if (token) {
            config.headers['Authorization'] = `Bearer ${token}`
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    response => {
        const res = response.data
        if (res.code === 200) {
            return res
        }
        if (res.code === 401) {
            if (userStore == null) {
                userStore = useUserStore()
            }
            userStore.logout()
        } else {
            return Promise.reject(new Error(res.msg || '错误'))
        }

    },
    error => {
        return Promise.reject(error)
    }
)

export default service
